const axios = require('axios');
const fs = require('fs');
const path = require('path');

async function assignImages() {
  try {
    // 登录获取token
    const loginResponse = await axios.post('http://localhost:3001/api/auth/login', {
      email: 'admin@example.com',
      password: '123456'
    });
    
    const token = loginResponse.data.data.token;
    console.log('登录成功，token:', token ? '已获取' : '未获取');
    
    if (!token) {
      console.log('登录失败');
      return;
    }
    
    // 获取菜品数据
    const itemsResponse = await axios.get('http://localhost:3001/api/menu/items', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    const items = itemsResponse.data.data?.items || [];
    console.log(`获取到 ${items.length} 个菜品`);
    
    // 获取图片目录中的文件
    const imageDir = '/Users/andylau/Dropbox/AppDevelopment/CMB250716/backend/public/images/menu';
    const imageFiles = fs.readdirSync(imageDir)
      .filter(file => file.endsWith('@1x.png')) // 只使用@1x版本
      .map(file => file.replace('@1x.png', ''));
    
    console.log(`找到 ${imageFiles.length} 个图片文件:`);
    imageFiles.forEach(img => console.log(`- ${img}`));
    
    // 菜品名称到图片的映射
    const nameToImageMap = {
      '雪浓汤': 'SeolleongTang',
      '凉拌冷面': 'Bibim_Naengmyeon',
      '麻辣年糕': 'Mala_Tteokbokki',
      '泡菜拉面': 'Kimchi_Ramen',
      '泡菜炒饭': 'Kimchi_Fried_Rice',
      '经典拌饭': 'Classic_Bibimbap',
      '韩式炸鸡套餐': 'Korean_Fried_Chicken_Set_',
      '蒜蓉酱油炸鸡': 'Fried_Chicken_Garlic_Soy',
      '芝士粉炸鸡': 'Fried_Chicken_CheesePowder',
      '鸡肉炖汤': 'Dakbokkeumtang',
      '鸡肉糖醋': 'chicken_tangsuyuk',
      '韩式海苔饭团': 'Korean_Seaweed_Rice_Ball',
      '炸饺子': 'fried_mandu',
      '紫菜卷': 'gimmari',
      '鱼糕': 'FishCake',
      '芝士炒年糕': 'cheese_fried_tteok',
      '辣炒年糕': 'spicy_fried_tteok',
      '排骨炖': 'galbi_jjim',
      '牛胸肉片': 'sliced_beef_brisket',
      'Highball': 'HighBallMpage_',
      '主菜C': 'MainPiceC_',
      // 新增映射
      '辣炖鸡腿': 'Dakbokkeumtang',
      '烧牛助骨': 'galbi_jjim',
      '紫菜饭团': 'Korean_Seaweed_Rice_Ball',
      '糖醋鸡块': 'chicken_tangsuyuk',
      '切片牛腩肉': 'sliced_beef_brisket',
      '炸紫菜卷': 'gimmari',
      '炸年糕 辣酱': 'spicy_fried_tteok',
      '炸年糕 芝士裹粉': 'cheese_fried_tteok',
      '炸鱼饼': 'FishCake',
      '蒜香鸡翅膀': 'Fried_Chicken_Garlic_Soy',
      '炸鸡- 芝士粉': 'Fried_Chicken_CheesePowder',
      '鱼饼锅': 'FishCake',
      '炸鸡中文名': 'Korean_Fried_Chicken_Set_',
      '饮料中文名': 'HighBallMpage_',
      '酒精类饮品中文名': 'HighBallMpage_'
    };
    
    let assignedCount = 0;
    let notFoundCount = 0;
    
    console.log('\n开始分配图片...');
    
    for (const item of items) {
      
      // 跳过已有图片的菜品
      if (item.image_url) {
        console.log(`跳过 ${item.name} - 已有图片: ${item.image_url}`);
        continue;
      }
      
      // 查找匹配的图片
      let imageName = nameToImageMap[item.name];
      
      // 如果没有直接映射，尝试模糊匹配
      if (!imageName) {
        const itemNameLower = item.name.toLowerCase();
        imageName = imageFiles.find(img => {
          const imgLower = img.toLowerCase();
          return imgLower.includes(itemNameLower) || itemNameLower.includes(imgLower);
        });
      }
      
      if (imageName && imageFiles.includes(imageName)) {
        const imageUrl = `/images/menu/${imageName}@1x.png`;
        
        try {
          // 获取完整的菜品数据
          const itemResponse = await axios.get(
            `http://localhost:3001/api/menu/items/${item.id}`,
            {
              headers: {
                'Authorization': `Bearer ${token}`
              }
            }
          );
          
          const fullItem = itemResponse.data.data;
          
          // 清理数据，处理null值
          const cleanedItem = {
            ...fullItem,
            image_url: imageUrl,
            // 处理必填字段的null值
            price: fullItem.price || 0,
            originalPrice: fullItem.originalPrice || undefined,
            image: fullItem.image || undefined,
            ingredients: fullItem.ingredients || undefined,
            spice_level: (fullItem.spice_level === 'mild' || fullItem.spice_level === null) ? undefined : fullItem.spice_level,
            calories: fullItem.calories || undefined,
            stock: fullItem.stock || undefined
          };
          
          // 移除undefined字段
          Object.keys(cleanedItem).forEach(key => {
            if (cleanedItem[key] === undefined) {
              delete cleanedItem[key];
            }
          });
          
          console.log(`准备更新菜品 ${item.name} (ID: ${item.id})`);
          console.log('更新数据:', JSON.stringify(cleanedItem, null, 2));
          
          // 更新菜品图片URL，保持其他字段不变
          const updateResponse = await axios.put(
            `http://localhost:3001/api/menu/items/${item.id}`,
            cleanedItem,
            {
              headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              }
            }
          );
          
          console.log('更新响应状态:', updateResponse.status);
          console.log('更新响应数据:', updateResponse.data);
          
          if (updateResponse.data.success) {
            console.log(`✅ ${item.name} -> ${imageUrl}`);
            assignedCount++;
          } else {
            console.log(`❌ 更新失败: ${item.name} - ${updateResponse.data.message}`);
            console.log('   更新响应:', updateResponse.data);
          }
        } catch (updateError) {
          console.log(`❌ 更新出错: ${item.name} - ${updateError.message}`);
          if (updateError.response) {
            console.log(`   状态码: ${updateError.response.status}`);
            console.log(`   响应数据:`, updateError.response.data);
          }
        }
      } else {
        console.log(`❌ 未找到匹配图片: ${item.name}`);
        notFoundCount++;
      }
    }
    
    console.log(`\n分配完成:`);
    console.log(`- 成功分配: ${assignedCount} 个`);
    console.log(`- 未找到图片: ${notFoundCount} 个`);
    console.log(`- 已有图片: ${items.filter(item => item.image_url).length} 个`);
    
  } catch (error) {
    console.error('分配图片时发生错误:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }
  }
}

assignImages();